package model;

import java.util.List;

import util.AppUtil;

import com.jfinal.plugin.activerecord.Model;

import constant.Msg;

public class Collection extends Model<Collection>{

	private static final long serialVersionUID = 5301075058773725966L;
	
	
	public static final Collection dao=new Collection();
	public static String findSQL="select * from collection where user_id = ? and recipe_id = ? ";
	public String  getCollections(int userId,String offset,String length) {
		try {
			List<Collection> collections=dao.find("select * from collection where user_id = ? limit ? , ?",userId,offset,length);
			return AppUtil.modelToJson(collections);
		} catch (Exception e) {
			e.printStackTrace();
			return Msg.ERROR_UNKNOWN;
		}
	}
	
	public String doCollect(int userId,String recipeId){
		try {
			List<Collection> collections=dao.find(findSQL,userId,recipeId);
			int size=collections.size();
			if (size==0) {
				dao.set("user_id", userId)
				.set("recipe_id", recipeId)
				.set("status", 1)
				.set("create_time", System.currentTimeMillis()/1000)
				.save();
				return Msg.SUCCESS_EXECUTE;
			}else {
				collections.get(0).set("status", 1).update();
				return Msg.SUCCESS_EXECUTE;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			return Msg.ERROR_UNKNOWN;
		}
	}
	
	public String cancel(int userId,String recipeId){
		try {
			List<Collection> collections=dao.find(findSQL,userId,recipeId);
			int size=collections.size();
			if (size==0)
			{
				collections.get(0).set("status", 0).update();
				return Msg.SUCCESS_EXECUTE;
			}else {
				return Msg.ERROR_DELETE_UNEXISTED;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return Msg.ERROR_UNKNOWN;
		}
	}
}
